package com.bree.erp.report.birt;

import java.io.InputStream;
import java.io.OutputStream;

import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.RenderOption;
import org.eclipse.birt.report.engine.api.ReportEngine;

public abstract class AbstractReport {
	
	public static final String DEFAULT_OUTPUT_FORMAT = "pdf";
	
	private IReportEngine engine;
	private IRenderOption options;
	
	public AbstractReport() {
		EngineConfig config = new EngineConfig();
        engine = new ReportEngine(config);
	}
	
	protected abstract InputStream getReportDesign();
	protected abstract String getReportName();
	protected abstract Object getDataSet();
	protected abstract void setParameterValues(IRunAndRenderTask task);
	
	@SuppressWarnings("unchecked")
	public void render(OutputStream os) throws EngineException {
		
		final IReportRunnable design = engine.openReportDesign(this.getReportDesign());

        // Create task to run and render the report,
        final IRunAndRenderTask task = engine.createRunAndRenderTask(design);
        
        // Set parent classloader for engine
        task.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
        		Birt.class.getClassLoader());
        
        task.getAppContext().put(this.getReportName(), this.getDataSet());
        
        getOptions().setOutputStream(os);
        
        task.setRenderOption(getOptions());
        
        setParameterValues(task);
        
        // run and render report
        task.run();
        task.close();
        
	}
	
	public IRenderOption getOptions() {
		
		if(options == null) {
			options = new RenderOption();
	        options.setOutputFormat(DEFAULT_OUTPUT_FORMAT);
		}
		
		return options;
	}
	
}
